<template>
  <div v-if="editOpen">
    <t-table :selected-row-keys="selectedRowKeys"
             @select-change="(val)=>{selectedRowKeys=val}" rowKey="id" :data="data"
             :columns="columns">
      <template #sort="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
      <template #expectResultType="{ row }">
        <t-cascader  clearable filterable
                    @change="()=>{ if(row.expectResultType!==''){row.expectResultTypeStatus='default'} }"
                    :status="row.expectResultTypeStatus" :keys="{value:'id'}" v-model="row.expectResultType"
                    :options="menuOptions">
          <div slot="tips" v-if="row.expectResultTypeStatus==='error'">不能为空</div>
        </t-cascader>
      </template>
      <template #note="{row}">
        <t-textarea
          @change="()=>{ if(row.note!==''){row.noteStatus='default'} }" :status="row.noteStatus"
          clearable :autosize="{minRows: 3}"
          v-model="row.note"
          placeholder="请输入内容"
        >
          <div slot="tips" v-if="row.noteStatus==='error'">不能为空</div>
        </t-textarea>
      </template>
      <template #count="{row}">
        <t-input-number v-if="row.expectResultType!==99" :allowInputOverLimit="false" clearable v-model="row.count"
                        :min="1"
                        placeholder="请输入"></t-input-number>
      </template>
      <template #empty>
        <span>暂无数据 请点击新增按钮</span>
      </template>
    </t-table>
    <div  style="margin-top: 10px" class="btn-group-inline">
      <t-button @click="addData">新增</t-button>
      <t-button @click="upData">上移</t-button>
      <t-button @click="downData">下移</t-button>
      <t-button @click="delData">删除</t-button>
    </div>
  </div>
  <div v-else>
    <t-table rowKey="id" :data="data"
             :columns="columns2">
      <template #sort="{ rowIndex }">
        {{ rowIndex + 1 }}
      </template>
      <template #expectResultType="{ row }">
        <!--        {{ row.expectResultType | filterByTree(menuOptions) }}-->
        <!--        <t-cascader v-if="rowIndex===0" status="error" readonly :keys="{value:'id'}" v-model="row.expectResultType" :options="menuOptions" ></t-cascader>-->
        <!--        <t-icon v-if="rowIndex===0" style="margin: 0px 5px" name="arrow-down"/>-->
        <t-cascader readonly :keys="{value:'id'}" v-model="row.expectResultType" :options="menuOptions"></t-cascader>

      </template>

      <template #count="{row}">
        <!--        <div v-if="rowIndex===0" style="color: red">{{ row.expectResultType!==99?row.count:'' }}</div>-->
        <!--        <t-icon v-if="rowIndex===0" style="margin: 0px 5px" name="arrow-down"/>-->
        <div> {{ row.expectResultType !== 99 ? row.count : '' }}</div>
      </template>
    </t-table>
  </div>
</template>

<script>
export default {
  name: "project-approach-expectResults",
  dicts: ["expect_result_type"],
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    editOpen: {
      type: Boolean,
      default: false
    },
    applyOpen: {
      type: Boolean,
      default: false
    },
    phaseType: {
      type: String,
      default: '1'
    },
    projectId: [String, Number],
  },
  data() {
    return {
      menuOptions: [],
      selectedRowKeys: [],
      dialogOpen: false,
      header: '新增预期研究成果及表达形式',
      visible: true,
      formData: {
        sort: null,
        name: '',
      },
      rules: {

        name: [
          {
            required: true,
            message: "不能为空",
          }
        ],
      },
      data: [],
      columns: [
        {
          colKey: 'row-select',
          type: 'single',
          title: "选择",
          width: 64,
          // checkProps: ({row}) => ({disabled: row.expectResultType === 1659106236653}),
        },
        {
          colKey: 'sort',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: 'expectResultType',
          title: "成果类型",
          align: "center",
          // ellipsis: true,
        },
        {
          colKey: 'note',
          title: "成果说明",
          align: "center",
        },
        {
          colKey: 'count',
          title: "数量",
          align: "center",
          ellipsis: true
        },
      ],
      columns2: [
        {
          colKey: 'sort',
          title: "序号",
          align: "center",
          width: 64
        },
        {
          colKey: 'expectResultType',
          title: "成果类型",
          align: "center",
          // ellipsis: true,
        },
        {
          colKey: 'note',
          title: "成果说明",
          align: "center",
        },
        {
          colKey: 'count',
          title: "数量",
          align: "center",
          ellipsis: true
        },
      ]
    }
  },
  watch: {
    data: {
      deep: true,
      immediate: true,
      handler(val) {
        const newData = this.data.map((val, index) => ({
          ...val,
          sort: index + 1,
          phaseType: this.phaseType,
          projectId: Number(this.projectId)
        }))
        this.$emit("input", newData);
      }
    },
    // value: {
    //   deep: true,
    //   immediate: true,
    //   handler(val) {
    //     if(val.length > 0 && this.data.length <= 0){
    //       this.data = val;
    //     }
    //   }
    // },
    projectId: {
      deep: true,
      immediate: true,
      handler(val) {
        if (val) {
          this.getData(val);
        }
      }
    },
  },
  async created() {
    await this.getTreeSelect();
  },
  methods: {
    getData() {
      this.$api.kjsf.project.projectExpectResultsGetByProjectIdAndPhaseType(Number(this.projectId), this.phaseType).then(res => {
        this.data = res.data;
        if (res.data.length <= 0 && this.phaseType !== '1' && this.applyOpen === true) {
          this.$api.kjsf.project.projectExpectResultsGetByProjectIdAndPhaseType(Number(this.projectId), Number(this.phaseType) - 1 > 0 ? Number(this.phaseType) - 1 : 1).then(res2 => {
            this.data = res2.data;
          }).catch((e) => {
            this.$message.error(e.toString());
          });
        }
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    /** 查询菜单下拉树结构 */
    getTreeSelect() {
      return this.$api.system.result.treeselect().then(response => {
        this.menuOptions = response.data;
      }).catch((e) => {
        this.$message.error(e.toString());
      });
    },
    checkData() {
      const isValidate = this.data.every((val, index) => {
        if (val.expectResultType === "") {
          this.$set(this.data[index], 'expectResultTypeStatus', 'error')
          this.$message.error(`预期研究成果及表达形式：第${index + 1}条成果类型不能为空`);
          return false;
        }
        this.$set(this.data[index], 'expectResultTypeStatus', 'default')
        if (val.note === "") {
          this.$set(this.data[index], 'noteStatus', 'error')
          this.$message.error(`预期研究成果及表达形式：第${index + 1}条成果说明不能为空`);
          return false;
        }
        this.$set(this.data[index], 'noteStatus', 'default')
        return true;
      });
      return isValidate
    },
    addData() {
      const newId = Number(new Date().getTime()) + Number(Math.random() * 10)
      this.data.push({
        id: newId,
        projectId: this.projectId,
        expectResultType: '',
        note: '',
        phaseType: this.phaseType,
        count: 1
      })
    },
    upData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[0].id === this.selectedRowKeys[0]) { // eslint-disable-line
        this.$message.warning("已是第一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index - 1)
      }
    },
    downData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      if (this.data[this.data.length - 1].id === this.selectedRowKeys[0]) {
        this.$message.warning("已是最后一行");
      } else {
        const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
        this.moveInArray(this.data, index, index + 1)
      }
    },
    delData() {
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning("请选择一行");
        return;
      }
      const index = this.data.findIndex((val) => val.id === this.selectedRowKeys[0])
      this.data.splice(index, 1)
      this.selectedRowKeys = [];
    },
    moveInArray(arr, ffrom, to) {
      // 删除当前的位置
      const item = arr.splice(ffrom, 1);
      // 确保还剩有元素移动
      if (!item.length) {
        this.$message.warning(`There is no item in the array at index ${ffrom}`);
      }
      // 移动元素到指定位置
      arr.splice(to, 0, item[0]);
    },
    onSubmit() {
      this.$refs.form.validate().then((validateResult) => {
        if (validateResult === true) {
          this.data.push({
            id: Number(new Date().getTime()) + Number(Math.random() * 10),
            ...this.formData
          })
          this.$refs.form.reset();
        } else {
          const firstError = Object.values(validateResult)[0]?.[0]?.message;
          this.$message.error(firstError);
        }
      })
    },
  }
}
</script>

<style lang="less" scoped>
//.t-form__item {
//  margin-bottom: var(--td-comp-margin-xxl);
//  margin-right: 0px
//}
.showText {

}
</style>
